﻿using System;
using System.Drawing;
using System.IO;
using System.Net;

namespace NetTrafficStatistics
{
	class Tools
	{
		internal const int Step = 15;
		internal const int Header = 20;
		internal const int Footer = 30;
		internal const int DateWidth = 70;
		internal const int DataWidth = 170;

		internal enum Units { B, KB, MB, GB }

		internal static readonly Font F = new Font ("Arial", 8);
		internal static readonly Font Fb = new Font ("Arial", 8, FontStyle.Bold);
		internal static readonly Font Fbu = new Font ("Arial", 8, FontStyle.Bold | FontStyle.Underline);
		internal static string LogFile;
		internal static string TmpFile;
		internal static int Counter;
		private static bool Started;


		internal static Units GetUnits (int index)
		{
			switch (index)
			{
				case 0: return Units.B;
				case 1: return Units.KB;
				case 2: return Units.MB;
				case 3: return Units.GB;
				default: return Units.B;
			}
		}

		internal enum Zone
		{
			None = 0,
			MyComputer = 1,
			Local = 2,
			Internet = 3
		}

		internal static Zone GetZone (IPAddress ip, IPAddress ip2, string ver)
		{
			if (ver != "IP v4")
				return Zone.None;

			if (ip.Equals (ip2))
				return Zone.MyComputer;

			var a = ip.GetAddressBytes ();
			var b = ip2.GetAddressBytes ();
			var zone = ParseIP (b);
			if (zone != Zone.None)
				return zone;

			return string.Format ("{0}{1}{2}", a[0], a[1], a[2]) == string.Format ("{0}{1}{2}", b[0], b[1], b[2]) ? Zone.Local : Zone.Internet;
		}

		private static Zone ParseIP (byte[] address)
		{
			switch (address[0])
			{
				case 10:
					return Zone.Local;

				case 172:
					if ((address[1] >= 16) && (address[1] <= 31))
						return Zone.Local;
					break;

				case 192:
					if (address[1] == 168)
						return Zone.Local;
					break;

				case 127:
					return Zone.MyComputer;
			}
			return Zone.None;
		}

		public static void WriteLogs (string s)
		{
			if (!Started)
			{
				File.AppendAllText (LogFile, "<Program started>\r\n");
				Started = true;
			}
			File.AppendAllText (LogFile, string.Format ("{0}\t{1}\r\n", DateTime.Now, s));
		}
	}
}
